
package com.hdoit.ares.web.acc.apis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.request.WxEntPayRequest;
import com.github.binarywang.wxpay.bean.result.WxEntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.hdoit.ares.logical.acc.model.AccountInfo;
import com.hdoit.ares.logical.acc.model.WithdrawParam;
import com.hdoit.ares.logical.acc.service.IAccountInfoService;
import com.hdoit.ares.logical.acc.service.IWithdrawApplyforService;
import com.hdoit.ares.logical.acc.service.IWithdrawParamService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.viewmodel.acc.Withdraw;
import com.hdoit.ares.web.cbase.AppWechatPayService;
import com.tennetcn.common.utils.DESedeCoder;
import com.tennetcn.common.utils.MD5Utils;
import com.tennetcn.common.utils.RandomUtils;
import com.tennetcn.component.webapi.BaseApi;
import com.tennetcn.component.webapi.ResponseModel;
import com.tennetcn.component.webapi.ResponseStatus;
import com.tennetcn.web.cbase.wechat.WechatPayService;

@Controller
@RequestMapping(value = "/api/v1/withdrawAndRecharge/",method = {RequestMethod.GET,RequestMethod.POST},produces="application/json;charset=utf-8")
@Api(value="/api/v1/WithdrawAndRecharge/")
@CrossOrigin(origins = "*",maxAge = 3600)
public class WithdrawAndRechargeAresApi extends BaseApi{

	private AppWechatPayService appWechatPayService;
	public AppWechatPayService getAppWechatPayService() {
		return appWechatPayService;
	}
	@Resource
	public void setAppWechatPayService(AppWechatPayService appWechatPayService) {
		this.appWechatPayService = appWechatPayService;
	}

	private IAccountInfoService accountInfoService;
	public IAccountInfoService getAccountInfoService() {
		return accountInfoService;
	}
	@Resource
	public void setAccountInfoService(IAccountInfoService accountInfoService) {
		this.accountInfoService = accountInfoService;
	}
	
	private ICustomerService customerService;
	public ICustomerService getCustomerService() {
		return customerService;
	}
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}
	
	private IWithdrawApplyforService withdrawApplyforService;
	public IWithdrawApplyforService getWithdrawApplyforService() {
		return withdrawApplyforService;
	}
	@Resource
	public void setWithdrawApplyforService(IWithdrawApplyforService withdrawApplyforService) {
		this.withdrawApplyforService = withdrawApplyforService;
	}
	
	private WechatPayService wechatPayService;
	public WechatPayService getWechatPayService() {
		return wechatPayService;
	}
	@Resource
	public void setWechatPayService(WechatPayService wechatPayService) {
		this.wechatPayService = wechatPayService;
	}
	
	private IWithdrawParamService withdrawParamService;
	public IWithdrawParamService getWithdrawParamService() {
		return withdrawParamService;
	}
	@Resource
	public void setWithdrawParamService(IWithdrawParamService withdrawParamService) {
		this.withdrawParamService = withdrawParamService;
	}

	private final String withdrawApi = "withdraw";
	private final String rechargeApi = "recharge";
	private final String toWithdrawApi = "toWithdraw";
	private final String toRechargeApi = "toRecharge";
	
	@ResponseBody
	@RequestMapping(value = withdrawApi)
	@ApiOperation(notes= withdrawApi,httpMethod = "POST" ,value = "进入充值页面时返回余额和提现须知")
	public String withdraw(){
		
		AccountInfo accountInfo = accountInfoService.queryModelByCustomerId(getLoginId());

		// 提现须知
		WithdrawParam minLimit = withdrawParamService.queryModelByHelpCode("minLimit");
		WithdrawParam perLimit = withdrawParamService.queryModelByHelpCode("perLimit");
		WithdrawParam withdrawCount = withdrawParamService.queryModelByHelpCode("withdrawCount");
		WithdrawParam totalMoney = withdrawParamService.queryModelByHelpCode("totalMoney");
		WithdrawParam minMoney = withdrawParamService.queryModelByHelpCode("minMoney");
		
		List<String> params = new ArrayList<String>();
		Field[] fields = WithdrawParam.class.getDeclaredFields();
		for(Field field : fields){
			params.add(field.getName());
		}
		ResponseModel rm = new ResponseModel();
		rm.put("balance", accountInfo.getBalance());
		rm.putObj("minLimit",minLimit,params);
		rm.putObj("perLimit",perLimit,params);
		rm.putObj("withdrawCount",withdrawCount,params);
		rm.putObj("totalMoney",totalMoney,params);
		rm.putObj("minMoney",minMoney,params);
		
		return rm.toJson();
	}
	
	
	@ResponseBody
	@RequestMapping(value = rechargeApi)
	@ApiOperation(notes= rechargeApi,httpMethod = "POST" ,value = "充值")
	public String recharge(){
		
		
		return null;
	}
	
	
	@ResponseBody
	@RequestMapping(value = toWithdrawApi)
	@ApiOperation(notes= toWithdrawApi,httpMethod = "POST" ,value = "处理提现")
	public String toWithdraw(@ApiParam("申请提现的金额（必填）") @RequestParam(value="money",required=true)Double money,@ApiParam("密码(必填)") @RequestParam(value="password",required=true)String password,HttpServletRequest req){
	
		System.err.println("这里是toWithdrawApi方法");
		
		ResponseModel rm = new ResponseModel();
		
		String customerId = getLoginId();
		Customer customer = customerService.queryModel(customerId);
		//查出数据库中的密码进行解密，解密为md5加密的结果(32位)
		String holdPsd = DESedeCoder.decrypt(customer.getPassword());
		//将页面传来的密码进行md5加密，并比较俩个密码是否相等
		String sendPsd = MD5Utils.encoderByMd5With32Bit(password);
		if(!holdPsd.equals(sendPsd)){
			rm.setStatus(ResponseStatus.dataError);
			rm.setMessage("密码错误");
			return rm.toJson();
		}
		
		
		HashMap<String,String> map = withdrawApplyforService.applyLimit(customer, money);
		//根据提现的金额做出相应的操作
		if("true".equals(map.get("result"))){
			rm.setStatus(ResponseStatus.success);
			rm.setMessage("ok");
			if(!"check".equals(map.get("key"))){
				//直接提现到账
				if(!directWithdraw(map.get("key"),req)){
					rm.setMessage("向微信发起提现请求失败！");
				}
			}else{
				//否则是后台在审核
				rm.setMessage(map.get("message"));
			}
			
			return rm.toJson();
		}
		
		//提现请求失败
		rm.setStatus(ResponseStatus.dataError);
		rm.setMessage(map.get("message"));
		return  rm.toJson();
	}
	
	
	@ResponseBody
	@RequestMapping(value = toRechargeApi)
	@ApiOperation(notes= toRechargeApi,httpMethod = "POST" ,value = "处理充值")
	public String toRecharge(){
		
		
		return null;
	}
	
	
	//用于直接提现的方法
	public boolean directWithdraw(String key, HttpServletRequest req){
		Withdraw withdraw = withdrawApplyforService.updateToConfirm(key);
		if (withdraw != null) {
			
			System.err.println("开始提现");
			WxEntPayRequest request = new WxEntPayRequest();

			request.setOpenid(withdraw.getAppOpenId());
			request.setCheckName("NO_CHECK");
			request.setNonceStr("" + System.currentTimeMillis()+ RandomUtils.randomInt(1000, 9999));
			request.setPartnerTradeNo("" + System.currentTimeMillis()+ RandomUtils.randomInt(1000, 9999));
			request.setAmount(withdraw.getAmount());
			request.setSpbillCreateIp("123.207.34.17");
			request.setDescription("提现");
			

			WxEntPayResult result = null;
			try {
				
				result = appWechatPayService.entPay(request);
			} catch (WxPayException e) {
				System.err.println("错误在这里");
				e.printStackTrace();
			}
			withdraw.setOutTradeNo(result.getPartnerTradeNo());

			// 根据回调结果做出相应操作.
			if (result != null && "SUCCESS".equals(result.getResultCode())&& "SUCCESS".equals(result.getReturnCode())) {

				withdraw.setPaymentNo(result.getPaymentNo());
				withdraw.setComment("提现到账成功");
				if (withdrawApplyforService.updateGoldBeanNum(withdraw, null)) {

					return true;
				}
			}

			withdraw.setComment("提现到账失败");
			withdrawApplyforService.updateForRollBack(withdraw, null);

			return false;
		}		
		return false;
	}
}
